# -*- coding: utf-8 -*-
# vim: ft=jinja

{#- Get the `tplroot` from `tpldir` #}
{%- set tplroot = tpldir.split('/')[0] %}
{#- Start imports as #}
{%- import_yaml tplroot ~ "/defaults.yaml" as default_settings %}
{%- import_yaml tplroot ~ "/osfamilymap.yaml" as osfamilymap %}
{%- import_yaml tplroot ~ "/osmap.yaml" as osmap %}
{%- import_yaml tplroot ~ "/osfingermap.yaml" as osfingermap %}

{#- Retrieve the config dict only once #}
{%- set _config = salt['config.get'](tplroot, default={}) %}

{%- set py_ver_settings = {
      2: {'pythonpkg': 'python-mysqldb'},
      3: {'pythonpkg': 'python3-mysqldb'},
    } %}

{%- set defaults = salt['grains.filter_by'](
      py_ver_settings,
      default=grains.pythonversion[0],
      merge=salt['grains.filter_by'](
        default_settings,
        default=tplroot,
        merge=salt['grains.filter_by'](
          osfamilymap,
          grain='os_family',
          merge=salt['grains.filter_by'](
            osmap,
            grain='os',
            merge=salt['grains.filter_by'](
              osfingermap,
              grain='osfinger',
              merge=salt['grains.filter_by'](
                _config,
                default='lookup'
              )
            )
          )
        )
      )
    )
%}

{%- set config = salt['grains.filter_by'](
      {'defaults': defaults},
      default='defaults',
      merge=_config
    )
%}

{%- set mysql = config %}

{#- Post-processing for specific non-YAML customisations #}
{%- if grains.os == 'MacOS' %}
{%-   set macos_user = salt['pillar.get']('mysql:user', salt['cmd.run']("stat -f '%Su' /dev/console")) %}
{%-   set macos_group = salt['pillar.get']('mysql:group', salt['cmd.run']("stat -f '%Sg' /dev/console")) %}
{%-   do mysql.macos.update({'user': macos_user}) %}
{%-   do mysql.macos.update({'group': macos_group}) %}
{%- endif %}
